<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2023-10-16 14:48:18
 * @LastEditors: swc
 * @LastEditTime: 2025-01-22 15:49:24
-->
<template>
  <div class="init-container">
    <div class="error-message" v-if="isErr">
      <h1>404</h1>
      <p>{{ errMsg }}</p>
    </div>
    <div class="init-container" v-else>
      <o-layout
        ref="layout"
        v-if="!$srv.utils.noValue(layoutConfig)"
        :config="layoutConfig"
      />
      <div class="center" v-if="$srv.utils.noValue(layoutConfig)">
        <div class="loader"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Tsrv, T_srv, ifs, ts, vue } from '@/services';

interface I_userInfo {
  uid: string;
  userName: string;
  depName: string;
}

@T_srv.comp
export default class oApp extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  // @T_srv.provide() addTabFunc = this.addTab;
  @T_srv.inject({ default: () => {} }) addTabFunc = this.addTab;

  /* 组件名 */
  private name: string = 'oApp';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  private getParams: URLSearchParams;

  private appName: string;

  private key: string;

  // 第几页，默认单据功能使用
  private pageNo: number = 1;

  private errMsg: string = '';

  private isErr: boolean = false;

  private layoutConfig: any = null;

  private allowFuns: Set<string> = new Set<string>([]);

  private userInfo: I_userInfo = {
    uid: '',
    userName: '',
    depName: ''
  };

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.handleParams();
    Tsrv.cookies.removeToken();
    document.title = Tsrv.getI18nByValue('单点登录');
  }

  private handleParams() {
    // 获取URL的GET参数
    this.getParams = new URLSearchParams(window.location.search);
    this.appName = this.getParams.get('name');
    this.key = this.getParams.get('key');
    this.pageNo = !Tsrv.noValue(this.getParams.get('pageNo'))
      ? Number(this.getParams.get('pageNo'))
      : 1;
    if (Tsrv.utils.noValue(this.appName) || Tsrv.utils.noValue(this.key)) {
      this.isErr = true;
      this.errMsg = Tsrv.getI18nByValue('传入的参数不正确,请与管理员联系!');
      return;
    }
    const p = this.getP();
    if (Tsrv.utils.noValue(p)) {
      return;
    }
    Tsrv.standardGetReq<ifs.I_restFulRes, any>(p, Tsrv.lexicon.url.getToken)
      .then(([res, err]) => {
        if (!Tsrv.utils.noValue(err) || res.code !== 200) {
          // this.$msg(err ?? res.message);
          this.errMsg = Tsrv.getI18nByValue('验证失败,请与管理员联系-验证失败');
          this.isErr = true;
        } else {
          this.$store
            .dispatch('Login', {
              userID: res.data.userID,
              userNo: res.data.userNo,
              userName: res.data.userName,
              dbName: res.data.dbName,
              token: res.data.token
            })
            .then(() => {
              this.storeSysInfo().then(ok => {
                if (ok) {
                  this.verifyUser().then(([_b, resp]) => {
                    if (_b) {
                      this.isErr = false;
                      this.loadFun();
                    } else {
                      resp && this.$msg(resp);
                      this.errMsg = resp;
                      this.isErr = true;
                    }
                  });
                }
              });
            });
        }
      })
      .catch(e => {
        this.isErr = true;
        this.errMsg = Tsrv.getI18nByValue('验证失败,请与管理员联系-网络异常');
      });
  }

  // 验证人员中航码
  private verifyUser(): Promise<[boolean, any]> {
    // “人员档案”表名 —— person_file  “中航码”字段 —— china_code
    return new Promise((resolve, reject) => {
      this.userInfo.uid = this.getParams.get('uid') ?? '';
      const uid = this.userInfo.uid;
      if (Tsrv.noValue(uid)) {
        resolve([false, Tsrv.getI18nByValue('未传入中航码')]);
      } else {
        const tableName = 'person_file';
        const gpd = new ts.T_getPartDataArg();
        const filters: Array<any> = [{ china_code: { $in: [uid] } }];
        gpd.setFunName(tableName).setLang(Tsrv.store.state.App.language);
        gpd.setPage(1, 99999).setDbType(Tsrv.globalVar.dbType.MYSQL);
        gpd.setFilter({ $and: filters });
        Tsrv.getData<any, ifs.I_getPartDataArg>(gpd)
          .then(([b, res, rows, m]) => {
            if (!b) {
              resolve([
                false,
                Tsrv.getI18nByValue('验证失败,请与管理员联系-用户验证失败')
              ]);
            } else {
              // 记录使用单点登录的人员信息
              let userInfo;
              if (Tsrv.noValue(rows)) {
                resolve([false, Tsrv.getI18nByValue('未找到此人员信息')]);
              } else {
                userInfo = rows[0];
                // 后续记录人员信息到···表中
                resolve([true, userInfo]);
              }
            }
          })
          .catch(er => {
            console.error(Tsrv.getI18nByValue('获取用户信息失败'), er);
          });
      }
    });
  }

  private async storeSysInfo(key: string = null): Promise<boolean> {
    const [resp, err] = await Tsrv.getSysInfo(key);
    if (err) {
      console.error('获取系统信息失败');
      this.$msg('-50013,FE,90');
      Tsrv.cookies.removeCookies;
      return false;
    }
    if (!resp.success) {
      this.$msg(resp.msg);
      Tsrv.cookies.removeCookies;
      return false;
    }
    const ok = await Tsrv.getStore().dispatch('setSysInfo', resp.data);
    !ok && console.error('获取系统信息失败');
    return ok;
  }

  private getP(): object {
    // if (!this.allowFuns.has(this.appName)) {
    //   this.isErr = true;
    //   this.errMsg = Tsrv.getI18nByValue(
    //     `此应用[${this.appName}]没有开放,请与管理员联系`
    //   );
    //   return null;
    // }
    return { key: this.key, name: this.appName };
  }

  // private loadFun() {
  //   this.$store
  //     .dispatch('getLayoutConfigAsync', {
  //       funid: null,
  //       field: this.appName,
  //       type: 'layout'
  //     })
  //     .then(res => {
  //       this.layoutConfig = Tsrv.utils.clone(res.current, true);
  //     })
  //     .catch(e => {
  //       this.isErr = true;
  //       this.errMsg = Tsrv.getI18nByValue('加载失败,请与管理员联系');
  //     });
  // }

  private loadFun() {
    this.$store
      .dispatch('getLayoutConfigAsync', {
        funid: null,
        field: this.appName,
        type: 'layout'
      })
      .then(res => {
        this.layoutConfig = Tsrv.utils.clone(res.current, true);
        const funType = res?.current?.name;
        if (funType && funType.toLowerCase() === 'basepanel') {
          setTimeout(() => {
            this.jumpToBill();
          }, 0);
        }
      })
      .catch(e => {
        this.isErr = true;
        this.errMsg = Tsrv.getI18nByValue('加载失败,请与管理员联系');
      });
  }

  // 单据跳转
  private jumpToBill() {
    const that = (this.$refs.layout as any).$children[0];
    if (
      that &&
      typeof that?.handleSearchTo === 'function' &&
      Tsrv.utils.isNumber(this.pageNo)
    ) {
      const timeout = this.pageNo === 0 ? 800 : 0;
      setTimeout(() => {
        if (this.pageNo === 0) {
          that.commitEvent('insert_actived');
        } else {
          that.handleSearchTo(this.pageNo);
        }
      }, timeout);
    }
  }

  public addTab(field: string) {
    // if (field === 'report_design') {
    //   window.open(`${this.$config.reportURL}list`);
    // } else {
    //   return new Promise(resolve => {
    //     // 调用getfun加载到缓存并取得配置this.layoutConfig
    //     this.$store
    //       .dispatch('getLayoutConfigAsync', {
    //         field,
    //         type: 'layout'
    //       })
    //       .then(res => {
    //         if (res) {
    //           // 获取配置
    //           this.layoutConfig = res.all;
    //           this.doAddTab(field);
    //           this.$nextTick(() => {
    //             resolve(this.getCurrentTab());
    //           });
    //         } else {
    //           resolve(false);
    //         }
    //       });
    //   });
    // }
    return undefined;
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$languageSetter.setLanguage(Tsrv.globalVar.i18n.zhCN);
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }
}
</script>
<style lang="scss" scoped>
.error-message {
  color: red;
  font-size: 20px;
  text-align: center;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loader {
  border: 16px solid #f3f3f3;
  border-top: 16px solid #3498db;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}
</style>
